package com.ikingtech.framework.sdk.sms.embedded.core.tencent;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.enums.sms.SmsPlatformTypeEnum;
import com.ikingtech.framework.sdk.enums.sms.SmsTemplateStatusEnum;
import com.ikingtech.framework.sdk.sms.embedded.AbstractSmsRequest;
import com.ikingtech.framework.sdk.sms.embedded.SmsSendArgs;
import com.ikingtech.framework.sdk.sms.embedded.SmsTemplateInfo;
import com.ikingtech.framework.sdk.utils.Tools;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class TencentSmsRequest extends AbstractSmsRequest {

    @Override
    public void send(SmsSendArgs args) {
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppId(this.config.getAppId());
        req.setSignName(args.getSignature());
        req.setTemplateId(args.getTemplateId());
        if (Tools.Coll.isNotBlankMap(args.getParams())) {
            Object[] originParams = args.getParams().values().toArray(new Object[0]);
            String[] paramSet = new String[args.getParams().size()];
            for (int i = 0; i < paramSet.length; i++) {
                paramSet[i] = (String) originParams[i];
            }
            req.setTemplateParamSet(paramSet);
        }
        req.setPhoneNumberSet(new String[]{args.getPhone()});
        req.setExtendCode(this.config.getExtendCode());
        try {
            SendSmsResponse resp = this.createClient().SendSms(req);
            for (SendStatus status : resp.getSendStatusSet()) {
                LogHelper.info("Tencent-SMS", "SendResult - {}", Tools.Json.toJsonStr(status));
            }
        } catch (TencentCloudSDKException e) {
            throw new FrameworkException(Tools.Str.format("腾讯云短信-发送异常[{}]", e.getMessage()));
        }
    }

    @Override
    public List<SmsTemplateInfo> listTemplate() {
        DescribeSmsTemplateListRequest req = new DescribeSmsTemplateListRequest();
        req.setInternational(0L);
        try {
            DescribeSmsTemplateListResponse resp = this.createClient().DescribeSmsTemplateList(req);
            return Tools.Array.convertList(resp.getDescribeTemplateStatusSet(), template -> {
                SmsTemplateInfo templateInfo = new SmsTemplateInfo();
                templateInfo.setTemplateId(Long.toString(template.getTemplateId()));
                templateInfo.setTemplateName(template.getTemplateName());
                if (0 == template.getStatusCode()) {
                    templateInfo.setStatus(SmsTemplateStatusEnum.APPROVED);
                } else if (1 == template.getStatusCode()) {
                    templateInfo.setStatus(SmsTemplateStatusEnum.APPROVING);
                } else {
                    templateInfo.setStatus(SmsTemplateStatusEnum.APPROVE_FAIL);
                }
                templateInfo.setContent(template.getTemplateContent());
                templateInfo.setParams(Tools.Str.findPlaceholder(template.getTemplateContent(), "{", "}"));
                return templateInfo;
            });
        } catch (TencentCloudSDKException e) {
            throw new FrameworkException(Tools.Str.format("腾讯云短信-查询模板异常[{}]", e.getMessage()));
        }
    }

    @Override
    public SmsPlatformTypeEnum platform() {
        return SmsPlatformTypeEnum.TENCENT;
    }

    private SmsClient createClient() {
        return new SmsClient(new Credential(this.config.getAppKey(), this.config.getAppSecret()), this.config.getEndpoint());
    }
}
